﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Account;
using TomNet.IMSC.Core.Contracts.Decoration;
using TomNet.IMSC.Core.Contracts.Finance;
using TomNet.IMSC.Core.Contracts.LowPriceHouse;
using TomNet.IMSC.Core.Contracts.NewHouse;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.Security;
using TomNet.IMSC.Model.ViewModels.Account;
using TomNet.IMSC.Model.DbModels.Account;
using TomNet.Web.Mvc.UI;
using TomNet.IMSC.Web.Filters;
using TomNet.IMSC.Model.DbModels.NewHouse;
using TomNet.IMSC.Model.DbModels.Decoration;
using TomNet.IMSC.Core.Contracts.Common;

namespace TomNet.IMSC.Web.Areas.Account.Controllers
{
    [Description("财务-佣金")]
    public class BrokerageController : BaseController
    {

        public IBrokerageRunningsContract BContract { set; get; }// 佣金流水
        public IStaffContract SContract { get; set; }
        public INewHouseRunningsContract NHContract { get; set; }
        public ILowPriceHouseRunningsContract LPHContract { get; set; }
        public IDecorationRunningsContract DContract { get; set; }
        public IFinanceRunningsContract FContract { get; set; }
        public IBrokerageSettleAccountsRunningsContract BSContract { get; set; }
        public IBuildingsBrokerageLevelContract BBLContract { get; set; }
        public IBuildingsBrokerageGroupContract BBGContract { get; set; }
        public IDecorationCompanyBrokerageLevelContract DBLContract { get; set; }
        public IDecorationCompanyBrokerageGroupContract DBGContract { get; set; }
        public IBrokerageTypeContract BTContract { get; set; }
        public IOutMoneyOrdersContract OMOContract { get; set; }
        public IOutMoneyOrdersRunningsContract OMORContract { get; set; }
        public IImagesContract ImagesContract { get; set; }

        // GET: Account/Brokerage
        [Description("财务-佣金列表面页")]
        [GlobalAuthorization]
        public ActionResult BrokerageList(int ModuleID, int BrokerageTypeID )
        {
            ViewBag.ModuleID = ModuleID;
            ViewBag.BrokerageTypeID = BrokerageTypeID;
            return View();
        }

        [Description("财务-获得佣金列表数据")]
        [HttpPost, AjaxOnly]
        [GlobalAuthorization]
        public ActionResult GetBrokerageList(int pageIndex, int pageSize, int ModuleID, string State,int BrokerageTypeID, string Search,string BeginTime,string EndTime)//, string search = "", int depid
        {
            IQueryable<BrokerageListModel> query = Enumerable.Empty<BrokerageListModel>().AsQueryable();
            DateTime bt = Convert.ToDateTime(BeginTime);
            DateTime et = Convert.ToDateTime(EndTime).AddDays(1);
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            switch (ModuleID)
            {
                case 1:
                    query = from e in BContract.Entities
                            join n in NHContract.Entities on e.RunningsID equals n.Id
                            join u1 in SContract.Entities on e.ConfirmStaffID equals u1.Id into eu1
                            from eu1d in eu1.DefaultIfEmpty()
                            join u2 in SContract.Entities on e.AuditingStaffID equals u2.Id into eu2
                            from eu2d in eu2.DefaultIfEmpty()
                            join u3 in SContract.Entities on n.OriginStaffID equals u3.Id into eu3
                            from eu3d in eu3.DefaultIfEmpty()
                            join u4 in SContract.Entities on n.SellStaffID equals u4.Id into eu4
                            from eu4d in eu4.DefaultIfEmpty()
                            where e.ModuleID == ModuleID && e.BrokerageTypeID == BrokerageTypeID && n.SubscribeTime >= bt && n.SubscribeTime <= et
                            select new BrokerageListModel
                            {
                                Amount = e.Amount,
                                AuditingStaffID = e.AuditingStaffID,
                                AuditingStaffName = eu2d.Name,
                                AuditingTime = e.AuditingTime,
                                ConfirmStaffID = e.ConfirmStaffID,
                                ConfirmStaffName = eu1d.Name,
                                ConfirmTime = e.ConfirmTime,
                                Id = e.Id,
                                ModuleID = e.ModuleID,
                                RunningsID = e.RunningsID,
                                State = e.State,
                                IntermediaryID = n.IntermediaryID,
                                IntermediaryName = n.IntermediaryName,
                                ItemName = n.BuildingName,
                                ItemTime=n.SubscribeTime,
                                ItemRemark = n.Remark,
                                CustomerName = n.CustomerName,
                                CustomerPhone = n.CustomerPhone,
                                UserName = n.UserName,
                                BrokerageTypeID = e.BrokerageTypeID,
                                IsReceipt = e.IsReceipt,
                                Tax = e.Tax,
                                SettledAmount = (from bs in BSContract.Entities where bs.BrokerageRunningsID == e.Id select new { a = bs.Amount }).Count() == 0 ? 0 : (from bs in BSContract.Entities where bs.BrokerageRunningsID == e.Id select new { a = bs.Amount }).Sum(x => x.a),
                                ItemPrice = n.TotalPrice,
                                AgentID = n.AgentID,
                                ItemTag = n.Address,
                                OriginStaffName = eu3d.Name,
                                SellStaffName = eu4d.Name,
                                ItemImageType1Number = ImagesContract.Entities.Count(p => p.GroupID == 3 && p.ImageType == 1 && p.InterfixID == n.Id && !p.IsDeleted),
                                ItemImageType2Number = ImagesContract.Entities.Count(p => p.GroupID == 3 && p.ImageType == 2 && p.InterfixID == n.Id && !p.IsDeleted),
                                ItemImageType3Number = ImagesContract.Entities.Count(p => p.GroupID == 3 && p.ImageType == 3 && p.InterfixID == n.Id && !p.IsDeleted)
                            };
                    break;
                case 2:
                case 3:
                    query = from e in BContract.Entities
                            join n in LPHContract.Entities on e.RunningsID equals n.Id
                            join u1 in SContract.Entities on e.ConfirmStaffID equals u1.Id into eu1
                            from eu1d in eu1.DefaultIfEmpty()
                            join u2 in SContract.Entities on e.AuditingStaffID equals u2.Id into eu2
                            from eu2d in eu2.DefaultIfEmpty()
                            join u3 in SContract.Entities on n.OriginStaffID equals u3.Id into eu3
                            from eu3d in eu3.DefaultIfEmpty()
                            join u4 in SContract.Entities on n.SellStaffID equals u4.Id into eu4
                            from eu4d in eu4.DefaultIfEmpty()
                            where e.ModuleID == ModuleID && e.BrokerageTypeID == BrokerageTypeID && n.SubscribeTime >= bt && n.SubscribeTime <= et
                            select new BrokerageListModel
                            {
                                Amount = e.Amount,
                                AuditingStaffID = e.AuditingStaffID,
                                AuditingStaffName = eu2d.Name,
                                AuditingTime = e.AuditingTime,
                                ConfirmStaffID = e.ConfirmStaffID,
                                ConfirmStaffName = eu1d.Name,
                                ConfirmTime = e.ConfirmTime,
                                Id = e.Id,
                                ModuleID = e.ModuleID,
                                RunningsID = e.RunningsID,
                                State = e.State,
                                IntermediaryID = n.IntermediaryID,
                                IntermediaryName = n.IntermediaryName,
                                ItemName = n.BuildingName,
                                ItemTime=n.SubscribeTime,
                                ItemRemark = n.Remark,
                                CustomerName = n.CustomerName,
                                CustomerPhone = n.CustomerPhone,
                                UserName = n.UserName,
                                BrokerageTypeID = e.BrokerageTypeID,
                                IsReceipt = e.IsReceipt,
                                Tax = e.Tax,
                                SettledAmount = (from bs in BSContract.Entities where bs.BrokerageRunningsID == e.Id select new { a = bs.Amount }).Count() == 0 ? 0 : (from bs in BSContract.Entities where bs.BrokerageRunningsID == e.Id select new { a = bs.Amount }).Sum(x => x.a),
                                ItemPrice = n.LowPrice,
                                AgentID = n.AgentID,
                                ItemTag = n.HouseNumber,
                                OriginStaffName = eu3d.Name,
                                SellStaffName = eu4d.Name,
                                ItemImageType1Number = ImagesContract.Entities.Count(p => p.GroupID == 5 && p.ImageType == 1 && p.InterfixID == n.Id && !p.IsDeleted),
                                ItemImageType2Number = ImagesContract.Entities.Count(p => p.GroupID == 5 && p.ImageType == 2 && p.InterfixID == n.Id && !p.IsDeleted),
                                ItemImageType3Number = ImagesContract.Entities.Count(p => p.GroupID == 5 && p.ImageType == 3 && p.InterfixID == n.Id && !p.IsDeleted)
                            };
                    break;
                case 4:
                    query = from e in BContract.Entities
                            join n in DContract.Entities on e.RunningsID equals n.Id
                            join u1 in SContract.Entities on e.ConfirmStaffID equals u1.Id into eu1
                            from eu1d in eu1.DefaultIfEmpty()
                            join u2 in SContract.Entities on e.AuditingStaffID equals u2.Id into eu2
                            from eu2d in eu2.DefaultIfEmpty()
                            join u3 in SContract.Entities on n.OriginStaffID equals u3.Id into eu3
                            from eu3d in eu3.DefaultIfEmpty()
                            join u4 in SContract.Entities on n.SellStaffID equals u4.Id into eu4
                            from eu4d in eu4.DefaultIfEmpty()
                            where e.ModuleID == ModuleID && e.BrokerageTypeID == BrokerageTypeID && n.SubscribeTime >= bt && n.SubscribeTime <= et
                            select new BrokerageListModel
                            {
                                Amount = e.Amount,
                                AuditingStaffID = e.AuditingStaffID,
                                AuditingStaffName = eu2d.Name,
                                AuditingTime = e.AuditingTime,
                                ConfirmStaffID = e.ConfirmStaffID,
                                ConfirmStaffName = eu1d.Name,
                                ConfirmTime = e.ConfirmTime,
                                Id = e.Id,
                                ModuleID = e.ModuleID,
                                RunningsID = e.RunningsID,
                                State = e.State,
                                IntermediaryID = n.IntermediaryID,
                                IntermediaryName = n.IntermediaryName,
                                ItemName = n.DecorationCompanyName,
                                ItemRemark=n.Remark,
                                CustomerName = n.CustomerName,
                                CustomerPhone = n.CustomerPhone,
                                UserName = n.UserName,
                                BrokerageTypeID = e.BrokerageTypeID,
                                IsReceipt = e.IsReceipt,
                                Tax = e.Tax,
                                SettledAmount = (from bs in BSContract.Entities where bs.BrokerageRunningsID == e.Id select new { a = bs.Amount }).Count() == 0 ? 0 : (from bs in BSContract.Entities where bs.BrokerageRunningsID == e.Id select new { a = bs.Amount }).Sum(x => x.a),
                                ItemPrice = n.TotalPrice,
                                ItemTime=n.SubscribeTime,
                                AgentID = n.AgentID,
                                ItemTag = n.CustomerAddress,
                                OriginStaffName = eu3d.Name,
                                SellStaffName = eu4d.Name,
                                ItemImageType1Number = ImagesContract.Entities.Count(p => p.GroupID == 7 && p.ImageType == 1 && p.InterfixID == n.Id && !p.IsDeleted),
                                ItemImageType2Number = ImagesContract.Entities.Count(p => p.GroupID == 7 && p.ImageType == 2 && p.InterfixID == n.Id && !p.IsDeleted),
                                ItemImageType3Number = ImagesContract.Entities.Count(p => p.GroupID == 7 && p.ImageType == 3 && p.InterfixID == n.Id && !p.IsDeleted)

                            };
                    break;
                case 5:
                    query = from e in BContract.Entities
                            join n in FContract.Entities on e.RunningsID equals n.Id
                            join u1 in SContract.Entities on e.ConfirmStaffID equals u1.Id into eu1
                            from eu1d in eu1.DefaultIfEmpty()
                            join u2 in SContract.Entities on e.AuditingStaffID equals u2.Id into eu2
                            from eu2d in eu2.DefaultIfEmpty()
                            join u3 in SContract.Entities on n.TransactStaffID equals u3.Id into eu3
                            from eu3d in eu3.DefaultIfEmpty()
                            join u4 in SContract.Entities on n.SellStaffID equals u4.Id into eu4
                            from eu4d in eu4.DefaultIfEmpty()
                            where e.ModuleID == ModuleID && e.BrokerageTypeID == BrokerageTypeID && n.CollectDataTime >=bt && n.CollectDataTime <= et
                            select new BrokerageListModel
                            {
                                Amount = e.Amount,
                                AuditingStaffID = e.AuditingStaffID,
                                AuditingStaffName = eu2d.Name,
                                AuditingTime = e.AuditingTime,
                                ConfirmStaffID = e.ConfirmStaffID,
                                ConfirmStaffName = eu1d.Name,
                                ConfirmTime = e.ConfirmTime,
                                Id = e.Id,
                                ModuleID = e.ModuleID,
                                RunningsID = e.RunningsID,
                                State = e.State,
                                IntermediaryID = n.IntermediaryID,
                                IntermediaryName = n.IntermediaryName,
                                ItemName = n.FinanceItemsName,
                                ItemTime=n.CollectDataTime,
                                ItemRemark = n.Remark,
                                CustomerName = n.CustomerName,
                                CustomerPhone = n.CustomerPhone,
                                UserName = n.UserName,
                                BrokerageTypeID = e.BrokerageTypeID,
                                IsReceipt = e.IsReceipt,
                                Tax = e.Tax,
                                SettledAmount = (from bs in BSContract.Entities where bs.BrokerageRunningsID == e.Id select new { a = bs.Amount }).Count()==0?0:(from bs in BSContract.Entities where bs.BrokerageRunningsID == e.Id select new { a = bs.Amount }).Sum(x => x.a),
                                ItemPrice = n.Price,
                                AgentID = n.AgentID,
                                ItemTag = n.Address,
                                OriginStaffName = eu3d.Name,
                                SellStaffName = eu4d.Name,
                                ItemImageType1Number = ImagesContract.Entities.Count(p => p.GroupID == 9 && p.ImageType == 1 && p.InterfixID == n.Id && !p.IsDeleted),
                                ItemImageType2Number = ImagesContract.Entities.Count(p => p.GroupID == 9 && p.ImageType == 2 && p.InterfixID == n.Id && !p.IsDeleted),
                                ItemImageType3Number = ImagesContract.Entities.Count(p => p.GroupID == 9 && p.ImageType == 3 && p.InterfixID == n.Id && !p.IsDeleted)

                            };
                    break;
                default:
                    break;
            }

            var total = query.Count();
            //if (State > 0)// 状态  1待审核    2已审核    3审核未通过    4已出款
            //{
            string[] s = State.Split(',');
            query = query.Where(p => s.Contains(p.State.ToString()));
            //}
            if (model.AgentId!=0)
            {
                query = query.Where(p => p.AgentID == model.AgentId);
            }
            if (!String.IsNullOrEmpty(Search))
            {
                query = query.Where(p =>  p.ItemName.IndexOf(Search) != -1 || p.IntermediaryName.IndexOf(Search) != -1 || p.UserName.IndexOf(Search) != -1 || p.CustomerName.IndexOf(Search) != -1 || p.CustomerPhone.IndexOf(Search) != -1);
            }
             

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : null;

            GridData<object> gridData = total > 0 ? new GridData<object>() { Total = total, Rows = query.ToList() } : new GridData<object>() { Total = total, Rows = new List<string>() };

            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }

        [Description("财务-佣金确认面页")]
        [GlobalAuthorization]
        public ActionResult ConfirmBrokerage(int ModuleID, int BrokerageTypeID, int ID,int State)
        {
            ViewBag.ModuleID = ModuleID;
            ViewBag.BrokerageTypeID = BrokerageTypeID;
            var bm = BContract.GetByKey(ID);
            ViewBag.RunningsID = bm.RunningsID;
            ViewBag.ID = ID;
            ViewBag.Amount = bm.Amount;
            ViewBag.State = State;
            int Num = 0;
            switch (ModuleID)
            {
                case 1:
                    var m = NHContract.GetByKey(bm.RunningsID);
                   Num = NHContract.Entities.Count(p => p.IntermediaryID == m.IntermediaryID && new int[] { 5, 6, 7, 8 }.Contains(p.State) && p.BuildingID == m.BuildingID);
                    break;
                case 2:
                case 3:
                    var m1 = LPHContract.GetByKey(bm.RunningsID);
                    Num = LPHContract.Entities.Count(p => p.IntermediaryID == m1.IntermediaryID && new int[] { 5, 6, 7, 8 }.Contains(p.State));
                    break;
                case 4:
                    var m2 = DContract.GetByKey(bm.RunningsID);
                    Num = DContract.Entities.Count(p => p.IntermediaryID == m2.IntermediaryID && new int[] { 5}.Contains(p.State) && p.DecorationCompanyID==m2.DecorationCompanyID);
                    break;
                case 5:
                    var m3 = FContract.GetByKey(bm.RunningsID);
                    Num = FContract.Entities.Count(p => p.IntermediaryID == m3.IntermediaryID && new int[] { 5 }.Contains(p.Progress));
                    break;
                default:
                    break;
            }
            ViewBag.Num = Num;
            return View();
        }
        [Description("财务-佣金分组等级列表")]
        [HttpPost, AjaxOnly]
        [GlobalAuthorization]
        public ActionResult GetBrokerageGroupLevelList(int ModuleID, int BrokerageTypeID, int RunningsID)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            IQueryable<BrokerageGroupLevelListModel> query = Enumerable.Empty<BrokerageGroupLevelListModel>().AsQueryable();
            switch (ModuleID)
            {
                case 1:
                    query = from n in NHContract.Entities
                            join bb in BBLContract.Entities on n.BuildingsBrokerageGroupID equals bb.BuildingsBrokerageGroupID
                            where bb.BrokerageTypeID == BrokerageTypeID && n.Id == RunningsID
                            select new BrokerageGroupLevelListModel
                            {
                                BrokerageGroupName = n.BuildingsBrokerageGroupName,
                                Achievement = bb.Achievement,
                                Award = bb.Award,
                                Percentage = bb.Percentage,
                                TotalPrice = n.TotalPrice,
                                Amount = n.TotalPrice * bb.Percentage + bb.Award,
                            };
                    break;
                case 2:
                case 3:
                    break;
                case 4:
                    query = from n in DContract.Entities
                            join bb in DBLContract.Entities on n.DecorationCompanyBrokerageGroupID equals bb.DecorationCompanyBrokerageGroupID
                            where bb.BrokerageTypeID == BrokerageTypeID && n.Id == RunningsID
                            select new BrokerageGroupLevelListModel
                            {
                                BrokerageGroupName = n.DecorationCompanyBrokerageGroupName,
                                Achievement = bb.Achievement,
                                Award = bb.Award,
                                Percentage = bb.Percentage,
                                TotalPrice = n.TotalPrice,
                                Amount = n.TotalPrice * bb.Percentage + bb.Award,
                            };
                    break;
                case 5:
                    break;
                default:
                    break;
            }

            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderBy(m => m.Achievement);


            GridData<object> gridData = total > 0 ? new GridData<object>() { Total = total, Rows = query.ToList() } : new GridData<object>() { Total = total, Rows = new List<string>() };

            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");


        }
        [Description("财务-确认佣金")]
        [HttpPost, AjaxOnly]
        [GlobalAuthorization]
        public ActionResult ConfirmBrokerageAsync(BrokerageRunnings entity)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);

            try
            {
                var query = BContract.CheckExists(m => m.Id.Equals(entity.Id));
                if (!query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "不存在对应佣金";
                }
                else
                {
                    var e = BContract.GetByKey(entity.Id);
                    e.State = entity.State;
                    e.Amount = entity.Amount;
                    e.ConfirmTime = DateTime.Now;
                    e.ConfirmStaffID = model.Id;
                    var count = BContract.Update(e);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "操作成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "操作失败";
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        [Description("财务-审核佣金")]
        [HttpPost, AjaxOnly]
        [GlobalAuthorization]
        public ActionResult AuditingBrokerageAsync(BrokerageRunnings entity)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            try
            {
                var query = BContract.CheckExists(m => m.Id.Equals(entity.Id));
                if (!query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "不存在对应佣金";
                }
                else
                {
                    var e = BContract.GetByKey(entity.Id);
                    e.State = entity.State;
                    e.Amount = entity.Amount;
                    e.AuditingTime = DateTime.Now;
                    e.AuditingStaffID = model.Id;
                    var count = BContract.Update(e);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "操作成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "操作失败";
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        [Description("财务-审核佣金")]
        [HttpPost, AjaxOnly]
        [GlobalAuthorization]
        public ActionResult ModifyReceipt(BrokerageRunnings entity)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            try
            {
                var query = BContract.CheckExists(m => m.Id.Equals(entity.Id));
                if (!query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "不存在对应佣金";
                }
                else
                {
                    var e = BContract.GetByKey(entity.Id);
                    if (e.IsReceipt==1)
                    {
                        e.IsReceipt = 0;
                        e.Tax = Convert.ToInt32(e.Amount * 0.1m);
                        if (BSContract.Entities.Count(p=>p.BrokerageRunningsID==e.Id)>0)
                        {
                            if (e.Amount-e.Tax-BSContract.Entities.Where(p=>p.BrokerageRunningsID==e.Id).Sum(p=>p.Amount)==0)
                            {
                                e.State = 4;
                            }
                        }
                    }
                    else
                    {
                        e.IsReceipt = 1;
                        e.Tax = 0;
                        if (e.State==4)
                        {
                            e.State = 3;
                        }
                    }
                    var count = BContract.Update(e);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "操作成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "操作失败";
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("财务-佣金结算面页")]
        [GlobalAuthorization]
        public ActionResult BrokerageSettleAccounts(int ID)
        {
            var bm = BContract.GetByKey(ID);
            ViewBag.RunningsID = bm.RunningsID;
            ViewBag.ID = ID;
            if (BSContract.Entities.Count(p => p.BrokerageRunningsID == bm.Id) == 0)
            {
                ViewBag.Amount = bm.Amount - bm.Tax;
            }
            else
            {
                ViewBag.Amount = bm.Amount - bm.Tax - BSContract.Entities.Where(p => p.BrokerageRunningsID == bm.Id).Sum(p => p.Amount);
            }
            return View();
        }
        [Description("财务-佣金结算")]
        [HttpPost, AjaxOnly]
        [GlobalAuthorization]
        public ActionResult BrokerageSettleAccountsAsync(BrokerageSettleAccountsRunnings entity)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            try
            {
                var query = BContract.CheckExists(m => m.Id.Equals(entity.BrokerageRunningsID));
                if (!query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "不存在对应费用";
                }
                else
                {
                    var e = BContract.GetByKey(entity.BrokerageRunningsID);

                    if (e.Amount - e.Tax - ((from bs in BSContract.Entities where bs.BrokerageRunningsID == e.Id select new { a = bs.Amount }).Count() == 0 ? 0 : (from bs in BSContract.Entities where bs.BrokerageRunningsID == e.Id select new { a = bs.Amount }).Sum(x => x.a)) - entity.Amount < 0)
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "结算金额大于未结算金额";
                    }
                    else if ((from a in OMORContract.Entities join b in OMOContract.Entities on a.OutMoneyOrdersID equals b.Id where b.State < 7 && a.BrokerageRunningsID == entity.BrokerageRunningsID select new { ID = a.Id }).Count() > 0)
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "该笔佣金已经出款单中，不能结算。";
                    }
                    else
                    {
                        var count = BSContract.Insert(new BrokerageSettleAccountsRunnings() { Amount = entity.Amount, BrokerageRunningsID = e.Id, CreatedTime = DateTime.Now, Remark = entity.Remark, StaffID = model.Id });
                        if (count > 0)
                        {
                            if (e.Amount - e.Tax - (from bs in BSContract.Entities where bs.BrokerageRunningsID == e.Id select new { a = bs.Amount }).Sum(x => x.a) == 0)
                            {
                                e.State = 4;
                            }
                            else
                            {
                                e.State = 3;
                            }
                            BContract.Update(e);
                            result.Type = AjaxResultType.Success;
                            result.Content = "操作成功";
                        }
                        else
                        {
                            result.Type = AjaxResultType.Error;
                            result.Content = "操作失败";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("财务-佣金结算历史面页")]
        [GlobalAuthorization]
        public ActionResult BrokerageSettleAccountsList(int ID)
        {
            var bm = BContract.GetByKey(ID);
            ViewBag.ID = ID;
            return View();
        }
        [Description("财务-佣金结算历史面页数据")]
        [HttpPost, AjaxOnly]
        [GlobalAuthorization]
        public ActionResult BrokerageSettleAccountsListAsync(BrokerageRunnings entity)//, string search = "", int depid
        {

            var query = from a in BSContract.Entities
                        join b in SContract.Entities on a.StaffID equals b.Id
                        where a.BrokerageRunningsID == entity.Id
                        select new { CreateTime = a.CreatedTime, Amount = a.Amount, StaffName = b.Name };

            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.CreateTime);

            GridData<object> gridData = total > 0 ? new GridData<object>() { Total = total, Rows = query.ToList() } : new GridData<object>() { Total = total, Rows = new List<string>() };

            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }

        [Description("财务-佣金分组列表面页")]
        [GlobalAuthorization]
        public ActionResult BrokerageGroupList(int ModuleID, int ItemID)
        {
            ViewBag.ModuleID = ModuleID;
            ViewBag.ItemID = ItemID;
            return View();
        }
        [Description("财务-佣金分组列表面页数据")]
        [HttpPost, AjaxOnly]
        [GlobalAuthorization]
        public ActionResult BrokerageGroupListAsync(int ModuleID,int ItemID)//, string search = "", int depid
        {
            IQueryable<BrokerageGroupListModel> query = Enumerable.Empty<BrokerageGroupListModel>().AsQueryable();
            switch (ModuleID)
            {
                case 1:
                    query = from a in BBGContract.Entities
                            where a.BuildingID == ItemID
                            select new BrokerageGroupListModel
                            {
                                ID = a.Id,
                                Brokerage = a.Brokerage,
                                ItemID = a.BuildingID,
                                ModuleID = ModuleID,
                                Name = a.Name,
                                PercentageType = a.PercentageType,
                                Remark = a.Remark,
                            };
                    break;
                case 4:
                    query = from a in DBGContract.Entities
                            where a.DecorationCompanyID == ItemID
                            select new BrokerageGroupListModel
                            {
                                ID = a.Id,
                                Brokerage = a.Brokerage,
                                ItemID = a.DecorationCompanyID,
                                ModuleID = ModuleID,
                                Name = a.Name,
                                PercentageType = a.PercentageType,
                                Remark = a.Remark,
                            };
                    break;
                default:
                    break;
            }
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.ID);

            GridData<object> gridData = total > 0 ? new GridData<object>() { Total = total, Rows = query.ToList() } : new GridData<object>() { Total = total, Rows = new List<string>() };

            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        [Description("财务-佣金分组添加页面")]
        [GlobalAuthorization]
        public ActionResult AddBrokerageGroup(int ModuleID, int ItemID, int ID = 0)
        {
            ViewBag.ModuleID = ModuleID;
            ViewBag.ItemID = ItemID;
            ViewBag.ID = ID;
            ViewBag.Name = "";
            ViewBag.Brokerage = "";
            ViewBag.Remark = "";
            ViewBag.PercentageType = 1;
            if (ID > 0)
            {
                switch (ModuleID)
                {
                    case 1:
                        BuildingsBrokerageGroup m = BBGContract.GetByKey(ID);
                        ViewBag.Name = m.Name;
                        ViewBag.Brokerage = m.Brokerage;
                        ViewBag.Remark = m.Remark;
                        ViewBag.PercentageType = m.PercentageType;
                        break;
                    case 4:
                        DecorationCompanyBrokerageGroup mm = DBGContract.GetByKey(ID);
                        ViewBag.Name = mm.Name;
                        ViewBag.Brokerage = mm.Brokerage;
                        ViewBag.Remark = mm.Remark;
                        ViewBag.PercentageType = mm.PercentageType;
                        break;
                    default:
                        break;
                }
            }
            return View();
        }
        [Description("财务-添加佣金分组")]
        [HttpPost, AjaxOnly]
        [GlobalAuthorization]
        public ActionResult AddBrokerageGroupAsync(BrokerageGroupListModel entity)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            try
            {
                int count = 0;
                switch (entity.ModuleID)
                {
                    case 1:
                        BuildingsBrokerageGroup m = new BuildingsBrokerageGroup();
                        m.Brokerage = entity.Brokerage;
                        m.BuildingID = entity.ItemID;
                        m.Name = entity.Name;
                        m.PercentageType = entity.PercentageType;
                        m.Remark = entity.Remark;
                        m.ShowIndex = 0;
                        m.Id = entity.ID;
                        if (entity.ID == 0)
                        {
                            count = BBGContract.Insert(m);
                        }
                        else
                        {
                            count = BBGContract.Update(m);
                        }
                        break;
                    case 4:
                        DecorationCompanyBrokerageGroup mm = new DecorationCompanyBrokerageGroup();
                        mm.Brokerage = entity.Brokerage;
                        mm.DecorationCompanyID = entity.ItemID;
                        mm.Name = entity.Name;
                        mm.PercentageType = entity.PercentageType;
                        mm.Remark = entity.Remark;
                        mm.ShowIndex = 0;
                        mm.Id = entity.ID;
                        if (entity.ID == 0)
                        {
                            count = DBGContract.Insert(mm);
                        }
                        else
                        {
                            count = DBGContract.Update(mm);
                        }
                        break;
                    default:
                        break;
                }

                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "操作成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "操作失败";
                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        [Description("财务-删除佣金分组")]
        [HttpPost, AjaxOnly]
        [GlobalAuthorization]
        public ActionResult DelBrokerageGroupAsync(int ModuleID,string IDs)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            try
            {
                int count = 0;
                string[] ids = IDs.Split(',');
                switch (ModuleID)
                {
                    case 1:
                        count = BBGContract.DeleteDirect(p => ids.Contains(p.Id.ToString()));
                        break;
                    case 4:
                        count = DBGContract.DeleteDirect(p => ids.Contains(p.Id.ToString()));
                        break;
                    default:
                        break;
                }

                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "操作成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "操作失败";
                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        [Description("财务-佣金分组列表面页")]
        [GlobalAuthorization]
        public ActionResult BrokerageGroupLevelList(int ModuleID, int BrokerageGroupID)
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            UpdateLoginModelAuthorityIds(model);

            ViewBag.ModuleID = ModuleID;
            ViewBag.BrokerageGroupID = BrokerageGroupID;
            List<BrokerageType> l = BTContract.Entities.Where(p => p.ModuleID == ModuleID).ToList();
            if (ModuleID == 1 && model.AuthorityIds.Split(',').Count(p => p == "140") == 0)
            {
                l.RemoveAll(p => p.Id == 1);
            }
            if (ModuleID == 4 && model.AuthorityIds.Split(',').Count(p => p == "255") == 0)
            {
                l.RemoveAll(p => p.Id == 9);
            }
            ViewBag.BrokerageTypeList = l;
            if (l.Count>0)
            {
                ViewBag.BrokerageTypeID = l[0].Id;
            }
            return View();
        }
        [Description("财务-佣金分组列表面页数据")]
        //[HttpPost, AjaxOnly]
        [GlobalAuthorization]
        public ActionResult BrokerageGroupLevelListAsync(int ModuleID, int BrokerageGroupID,int BrokerageTypeID)//, string search = "", int depid
        {
            IQueryable<BrokerageGroupLevelListModel> query = Enumerable.Empty<BrokerageGroupLevelListModel>().AsQueryable();
            switch (ModuleID)
            {
                case 1:
                    query = from a in BBLContract.Entities
                            where a.BuildingsBrokerageGroupID == BrokerageGroupID && a.BrokerageTypeID == BrokerageTypeID
                            select new BrokerageGroupLevelListModel
                            {
                                ID = a.Id,
                                Achievement = a.Achievement,
                                Award = a.Award,
                                Percentage = a.Percentage
                            };
                    break;
                case 4:
                    query = from a in DBLContract.Entities
                            where a.DecorationCompanyBrokerageGroupID == BrokerageGroupID && a.BrokerageTypeID == BrokerageTypeID
                            select new BrokerageGroupLevelListModel
                            {
                                ID = a.Id,
                                Achievement = a.Achievement,
                                Award = a.Award,
                                Percentage = a.Percentage
                            };
                    break;
                default:
                    break;
            }
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderBy(m => m.Achievement);

            GridData<object> gridData = total > 0 ? new GridData<object>() { Total = total, Rows = query.ToList() } : new GridData<object>() { Total = total, Rows = new List<string>() };

            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        [Description("财务-佣金分组等级添加页面")]
        [GlobalAuthorization]
        public ActionResult AddBrokerageGroupLevel(int ModuleID, int BrokerageGroupID, int BrokerageTypeID)
        {
            ViewBag.ModuleID = ModuleID;
            ViewBag.BrokerageGroupID = BrokerageGroupID;
            ViewBag.BrokerageTypeID = BrokerageTypeID;
            return View();
        }
        [Description("财务-添加佣金分组等级")]
        [HttpPost, AjaxOnly]
        [GlobalAuthorization]
        public ActionResult AddBrokerageGroupLevelAsync(int ModuleID, int BrokerageGroupID, int BrokerageTypeID ,int Achievement,decimal Percentage,int Award)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            try
            {
                int count = 0;
                switch (ModuleID)
                {
                    case 1:
                        BBLContract.DeleteDirect(p => p.Achievement == Achievement && p.BrokerageTypeID == BrokerageTypeID && p.BuildingsBrokerageGroupID == BrokerageGroupID);
                        BuildingsBrokerageLevel m = new BuildingsBrokerageLevel();
                        m.Achievement = Achievement;
                        m.Award = Award;
                        m.BrokerageTypeID = BrokerageTypeID;
                        m.BuildingsBrokerageGroupID = BrokerageGroupID;
                        m.Percentage = Percentage;
                        count = BBLContract.Insert(m);
                        break;
                    case 4:
                        DBLContract.DeleteDirect(p => p.Achievement == Achievement && p.BrokerageTypeID == BrokerageTypeID && p.DecorationCompanyBrokerageGroupID == BrokerageGroupID);
                        DecorationCompanyBrokerageLevel mm = new DecorationCompanyBrokerageLevel();
                        mm.Achievement = Achievement;
                        mm.Award = Award;
                        mm.BrokerageTypeID = BrokerageTypeID;
                        mm.DecorationCompanyBrokerageGroupID = BrokerageGroupID;
                        mm.Percentage = Percentage;
                        count = DBLContract.Insert(mm);
                        break;
                    default:
                        break;
                }

                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "操作成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "操作失败";
                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        [Description("财务-删除佣金分组等级")]
        [HttpPost, AjaxOnly]
        [GlobalAuthorization]
        public ActionResult DelBrokerageGroupLevel(int ModuleID, int ID)//, string search = "", int depid
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            try
            {
                int count = 0;
                switch (ModuleID)
                {
                    case 1:
                        count=BBLContract.Delete(ID);
                        break;
                    case 4:
                        count=DBLContract.Delete(ID);
                        break;
                    default:
                        break;
                }

                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "操作成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "操作失败";
                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

    }
}